/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yaps.petstore.service;

import com.yaps.petex.transport.Delivery;
import com.yaps.petex.transport.DeliveryPlace;
import com.yaps.petstore.dao.OrderDAO;
import com.yaps.petstore.dto.CartItem;
import com.yaps.petstore.entity.catalog.Category;
import com.yaps.petstore.entity.customer.Address;
import com.yaps.petstore.entity.customer.Customer;
import com.yaps.petstore.entity.order.CreditCard;
import com.yaps.petstore.entity.order.Order;
import com.yaps.petstore.entity.order.OrderLine;
import com.yaps.petstore.exception.ValidationException;
import com.yaps.petstore.util.Constants;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.jms.core.JmsTemplate;

/*
 * @author belhassine
 */

@Service("OrderService")
public class OrderService implements IOrderService {

    private final String cname = this.getClass().getName();
    private Logger logger = Logger.getLogger(Constants.LOGGER_STATELESS);
    @Autowired
    OrderDAO orderDAO;

    @Autowired

    private Delivery delivery;


    @Override
    public Order createOrder(Customer customer, Address deliveryAddress, CreditCard creditCard, List<CartItem> cartItems) {
        final String mname = "createOrder";
        logger.entering(cname, mname, cartItems.size());

        // On s'assure de la validité des paramètres
        if (cartItems == null || cartItems.size() == 0) {
            throw new ValidationException("Shopping cart is empty");
        }

        // Creation du bon de commande
        Order order = new Order(customer, deliveryAddress, creditCard);

        // A partir du panier electronique on crée les lignes du bon de commande
        List<OrderLine> orderLines = new ArrayList<OrderLine>();

        for (CartItem cartItem : cartItems) {
            orderLines.add(new OrderLine(cartItem.getQuantity(), cartItem.getItem()));
        }
        order.setOrderLines(orderLines);

        System.out.println(orderLines.get(0));
        // L'objet est persisté en base de données
        order = orderDAO.createOrder(order);


        publishOrder(order);
        notifyTransporter(order);

        logger.exiting(cname, mname, order);
        return order;
    }

    @Override
    public Order findOrder(Long orderId) {
        return orderDAO.findOrder(orderId);
    }

    @Override
    public void deleteOrder(Order order) {
        final String mname = "deleteOrder";
        logger.entering(cname, mname, order);

        // On s'assure de la validité des paramètres
        if (order == null) {
            throw new ValidationException("Order object is null");
        }

        // On supprime l'objet de la base de données
        orderDAO.deleteOrder(order);

        logger.exiting(cname, mname);
    }

    @Override
    public List<Order> findOrders() {
        final String mname = "findOrders";
        logger.entering(cname, mname);


        List<Order> orders;

        orders = orderDAO.findOrders();

        logger.exiting(cname, mname, orders.size());
        return orders;
    }

    private void publishOrder( final Order order) {
        System.out.println("Dans la methode publishOrder");
        ApplicationContext context = new ClassPathXmlApplicationContext("com/yaps/petstore/spring-jms.xml");

        JmsTemplate jmstemplate = (JmsTemplate) context.getBean("jmsTemplate");
        
        MessageCreator mc = new MessageCreator() {

            @Override
            public Message createMessage(Session sn) throws JMSException {
                // Create a message
                ObjectMessage objectMessage = sn.createObjectMessage();
                // Add in header the distinct categories
                Set<Category> categories = Order.getDistinctCategories(order);
                for (Category c : categories) {
                    objectMessage.setBooleanProperty(c.getName(), true);
                }
                objectMessage.setObject(order);
                return objectMessage;
            }
        };
        jmstemplate.send(mc);
       
    }
//         

    private void notifyTransporter(Order order) {
        String mname = "notifyTransporter";
        logger.entering(cname, mname, order);

        DeliveryPlace from = new DeliveryPlace();
        DeliveryPlace to = new DeliveryPlace();

        from.setContact(Constants.COMPANY_NAME);
        from.setStreet(Constants.COMPANY_STREET);
        from.setCity(Constants.COMPANY_CITY);
        from.setState(Constants.COMPANY_STATE);
        from.setZipcode(Constants.COMPANY_ZIPCODE);
        from.setCountry(Constants.COMPANY_COUNTRY);

        to.setContact(order.getCustomer().getLastname());
        to.setStreet(order.getDeliveryAddress().getStreet1());
        to.setCity(order.getDeliveryAddress().getCity());
        to.setState(order.getDeliveryAddress().getState());
        to.setZipcode(order.getDeliveryAddress().getZipcode());
        to.setCountry(order.getDeliveryAddress().getCountry());


        delivery.deliverItems(from, to, order.getId().toString());
        logger.info("Delivery Service has been called. ");

        logger.exiting(cname, mname);
    }
}
